#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 10005;

struct Node {
  int val;
  int ch[2];
  ll sum;
} tr[N];
int tot;
vector<int> a_in;
vector<int> a_post;
map<int, int> val2idx;
int newnode(int val) {
  ++tot;
  tr[tot].val = val;
  tr[tot].ch[0] = tr[tot].ch[1] = 0;
  tr[tot].sum = 0;
  return tot;
}
int build_tree(int l1, int l2, int len) {
  if (len <= 0) return 0;
  int r1 = l1 + len - 1;
  int r2 = l2 + len - 1;
  int val = a_post[r2];
  int p = newnode(val);
  int mid = val2idx[val];
  tr[p].ch[0] = build_tree(l1, l2, mid - l1);
  tr[p].ch[1] = build_tree(mid + 1, mid + l2 - l1, r1 - mid);
  return p;
}
ll sum;
int ans;
void dfs(int p, ll prefix) {
  tr[p].sum = prefix + tr[p].val;
  if (!tr[p].ch[0] && !tr[p].ch[1]) {
    if (tr[p].sum < sum || (tr[p].sum == sum && tr[p].val < ans)) {
      sum = tr[p].sum;
      ans = tr[p].val;
    }
    return;
  }
  if (tr[p].ch[0]) dfs(tr[p].ch[0], tr[p].sum);
  if (tr[p].ch[1]) dfs(tr[p].ch[1], tr[p].sum);
}
void parse(string& line, vector<int>& a) {
  a.clear();
  stringstream ss(line);
  int x;
  while (ss >> x) a.push_back(x);
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  string line1, line2;
  while (getline(cin, line1) && getline(cin, line2)) {
    tot = 0;
    val2idx.clear();
    parse(line1, a_in);
    parse(line2, a_post);
    rep(i, 0, a_in.size() - 1) val2idx[a_in[i]] = i;
    int root = build_tree(0, 0, a_in.size());
    sum = 1e18;
    dfs(root, 0);
    cout << ans << endl;
  }
  return 0;
}